package com.meida.module.bus.provider.api.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.module.bus.client.entity.*;
import com.meida.module.bus.client.entity.srmapi.psmtosrm.*;
import com.meida.module.bus.provider.api.util.ApiConstants;
import com.meida.module.bus.provider.api.util.PmsApiUtil;
import com.meida.module.bus.provider.api.util.PmsLogUtil;
import com.meida.module.bus.provider.api.util.PmsToolUtil;
import com.meida.module.bus.provider.service.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Service
public class PmsSrmApiService {

    @Autowired
    private BusPurchaseDetailsService busPurchaseDetailsService;
    // PMS-材料关联SRM表数据
    @Autowired
    private BusMaterialSrmService busMaterialSrmService;
    @Autowired
    private BusMaterialSrmSubService busMaterialSrmSubService;
    // PMS-材料关联SRM表数据-送货单
    @Autowired
    private BusDeliverSrmService busDeliverSrmService;
    @Autowired
    private BusMaterialPlan100Service busMaterialPlan100Service;
    @Autowired
    private BusMaterialPlan200Service busMaterialPlan200Service;
    @Autowired
    private BusMaterialPackage100Service package100Service;
    @Autowired
    private BusMaterialPackage200Service package200Service;
    @Autowired
    private PmsLogUtil pmsLogUtil;
    @Autowired
    private PmsApiUtil pmsApiUtil;
    @Autowired
    private PmsSrmApiSubService pmsSrmApiSubService;
    @Autowired
    private BusProjectService busProjectService;
    @Autowired
    private BusVersionService busVersionService;
    @Autowired
    private BusProjectSupplierService busProjectSupplierService;
    @Autowired
    private BusSupplierService supplierService;
    @Autowired
    private BusProjectPackSyncSrmService projectPackSyncSrmService;
    @Autowired
    private BusReportService busReportService;

    @ApiOperation(value = "需求申请明细关闭接口 : pms01")
    public void pms01(PmsSrm01 pmsSrm01) {
        // 关闭部分或全部材料申请
        pmsSrmApiSubService.closePurchaseOrder(pmsSrm01);
        // 回写材料计划的已采购数量
        pmsSrmApiSubService.backWriteMaterialBaseData(pmsSrm01);
    }

    //    业务场景：
    //        1.材料在SAP平衡利库后，回传数据到SRM，在SRM端成功处理完数据后（生成/更新采购申请），调用PMS系统接口接受到的SAP利库的信息，回传到PMS系统。
    //        2.一个需求计划申请生成一个采购申请。
    //        3.判断是否存在调拨，
    //          存在调拨：更新材料申请的在途，到货，材料计划的在途，到货
    //    接收方处理：
    //        1.PMS接收数据成功且处理成功后返回0，错误则返回1，异常返回2；错误和异常返回错误/异常信息。
    @ApiOperation(value = "SRM采购申请同步接口 : pms02")
    public void pms02(PmsSrm02 pmsSrm02) {
        List<BusMaterialSrm> busMaterialSrmList = Lists.newArrayList();
        BusPurchaseDetails detailHeader = busPurchaseDetailsService.getById(pmsSrm02.getDetail().get(0).getPurchaseDetailsId());
        BusProject busProject = busProjectService.getById(detailHeader.getProjectId());
        Object planData = pmsApiUtil.getMaterialPlanDataObj(pmsSrm02.getDetail().get(0).getPurchaseDetailsId(), null, null);
        pmsSrm02.getDetail().stream().forEach(detailReq -> {
            BusPurchaseDetails detailObj = busPurchaseDetailsService.getById(detailReq.getPurchaseDetailsId());
            // SRM关联表更新对象设定
            BusMaterialSrm busMaterialSrm = pmsSrmApiSubService.getSetBusMaterialSrmForPm02(detailReq, pmsSrm02);
            busMaterialSrm.setProjectId(detailObj.getProjectId());
            busMaterialSrm.setProjectCode(busProject.getProjectCode());
            busMaterialSrm.setProjectName(busProject.getProjectName());
            busMaterialSrm.setMajorCode(PmsToolUtil.getStrValue(planData, ApiConstants.INVOKE_GET_MAJORCODE));
            busMaterialSrm.setMajorName(PmsToolUtil.getStrValue(planData, ApiConstants.INVOKE_GET_MATERIALNAME));
            busMaterialSrm.setPackageCode(PmsToolUtil.getStrValue(planData, ApiConstants.INVOKE_GET_PACKAGENO));
            busMaterialSrm.setPackageName(PmsToolUtil.getStrValue(planData, ApiConstants.INVOKE_GET_PACKAGENAME));

            // 材料关联主key
            busMaterialSrm.setMaterialPlanId(detailObj.getMaterialId());
            busMaterialSrmList.add(busMaterialSrm);
        });
        // SRM关联表更新
        pmsApiUtil.saveOrUpDateBusMaterialSrm(busMaterialSrmList);
        // 判断是否存在调拨
        // 存在调拨：更新材料申请的在途，到货，材料计划的在途，到货
        pmsSrmApiSubService.pms02Sub01(pmsSrm02);
    }

    //    业务场景：
    //
    //        1.合同类型为开口合同时，合同工作流审核通过后，调用PMS系统接口将合同信息传到PMS系统。
    //    接收方处理：
    //        1.PMS接收数据成功且处理成功后返回0，错误则返回1，异常返回2；错误和返回错误/异常信息。
    //        2.工程师在PMS点击【开口订单】下达执行
    @ApiOperation(value = "SRM开口合同同步 : pms03")
    public void pms03(PmsSrm03 pmsSrm03) {
        BusMaterialSrm header = pmsApiUtil.getBusMaterialSrm(pmsSrm03.getDetail().get(0).getPurchaseId(), pmsSrm03.getDetail().get(0).getPurchaseDetailsId());
        Integer ver = pmsApiUtil.getLastVer(header.getProjectId(), 0) ? ApiConstants.VER_100 : ApiConstants.VER_200;
        List<Object> updObjs = Lists.newArrayList();
        List<BusMaterialSrmSub> busMaterialSrmSubs = Lists.newArrayList();
        pmsSrm03.getDetail().stream().forEach(detailReq -> {
            // 获取材料对象
            Object updObj = pmsApiUtil.getMaterialPlanDataObj(detailReq.getPurchaseDetailsId(), null, null);
            // 更新材料对象的开口flg为open
            PmsToolUtil.setValue(updObj, ApiConstants.INVOKE_SET_ORDERFLG, ApiConstants.ORDER_FLG_ON);
            updObjs.add(updObj);

            // SRM合同采购订单关联表更新
            BusMaterialSrm busMaterialSrm = pmsApiUtil.getBusMaterialSrm(detailReq.getPurchaseId(), detailReq.getPurchaseDetailsId());
            BusMaterialSrmSub busMaterialSrmSub = new BusMaterialSrmSub();
            busMaterialSrmSub.setPurchaseId(detailReq.getPurchaseId());
            busMaterialSrmSub.setPurchaseDetailsId(detailReq.getPurchaseDetailsId());
            // 关联主表主键
            busMaterialSrmSub.setBusMaterialSrmId(busMaterialSrm.getBusMaterialSrmId());
            // 材料计划主key
            busMaterialSrmSub.setMaterialPlanId(busMaterialSrm.getMaterialPlanId());
            // 标识当前记录为开口合同
            busMaterialSrmSub.setOrderFlg(ApiConstants.ORDER_FLG_ON);

            // SRM合同编码
            busMaterialSrmSub.setContractNo(pmsSrm03.getContractNo());
            // SRM合同ID
            busMaterialSrmSub.setContractsId(pmsSrm03.getContractsId());
            // SRM合同明细ID
            busMaterialSrmSub.setContractsmatdtlId(detailReq.getContractsMatDtlId());
            // SRM合同行号
            busMaterialSrmSub.setContractRowno(detailReq.getRowNo());
            // 版本
            busMaterialSrmSub.setVer(ver);
            // 订单数量
            busMaterialSrmSub.setOrderQty(detailReq.getOrderQty());
            // 剩余数量
            busMaterialSrmSub.setOrderSurplusQty(detailReq.getOrderQty());

            // 物料名称
            busMaterialSrmSub.setMaterialName(PmsToolUtil.getStrValue(updObj, ApiConstants.INVOKE_GET_MATERIALNAME));
            // 物料代码
            busMaterialSrmSub.setMaterialCode(PmsToolUtil.getStrValue(updObj, ApiConstants.INVOKE_GET_MATERIALCODE));
            // 物料WBS
            busMaterialSrmSub.setWbs(PmsToolUtil.getStrValue(updObj, ApiConstants.INVOKE_GET_MATERIALWBSCODE));

            busMaterialSrmSubs.add(busMaterialSrmSub);
        });
        // 更新材料计划数据
        pmsApiUtil.updatePlanPackageData(updObjs, ApiConstants.INT_ZERO, ver);

        // 更新SRM关联表主表
        // 更新SRM关联表主子表
        busMaterialSrmSubService.saveBatch(busMaterialSrmSubs);
    }

    //    业务场景：
    //        1：采购订单，在供应商点击【确认】后，同步到最新的采购订单信息到PMS，同时自动根据采购订单明细自动创建送货单并将送货单信息回传回PMS。※供应商如果不接收拒绝订单时，不要回传PMS。
    //        2：采购订单整单【取消/订单完成】的时候，同步信息到PMS。
    //        3：采购订单明细行，【关闭/取消关闭】的时候，同步信息到PMS。
    //        4：合同变更后，采购订单信息发生变更的时候，同步信息到PMS。
    //    接收方处理：
    //        1.PMS接收数据成功且处理成功后返回0，错误则返回1，异常返回2；错误和异常返回错误/异常信息。
    @ApiOperation(value = "SRM订单送货单信息同步 : pms04")
    public void pms04(PmsSrm04 pmsSrm04) throws Exception {
        // 分包
        // if (1 == pmsSrm04.getPlanFlg()) {
        if (StrUtil.startWith(pmsSrm04.getPurchaseOrderNo(), "47")
            ||
            StrUtil.startWith(pmsSrm04.getPurchaseOrderNo(), "48")) {
            BusProject busProject = getBusProjectForPms04(pmsSrm04.getDetail().get(0).getVer(), pmsSrm04.getDetail().get(0).getMaterialPackageIds());
            Object headerPackageData = pmsApiUtil.getPackagePalnData(pmsSrm04.getDetail().get(0).getVer(), pmsSrm04.getDetail().get(0).getMaterialPackageIds());
            String majorCode = PmsToolUtil.getStrValue(headerPackageData, ApiConstants.INVOKE_GET_MAJORCODE);
            String packageNo = PmsToolUtil.getStrValue(headerPackageData, ApiConstants.INVOKE_GET_PACKAGENO);
            BusProjectSupplier busProjectSupplier = pmsApiUtil.getBusProjectSupplier(busProject.getProjectId(), majorCode, packageNo);
            // 判断当前同步订单信息是否为变更信息
            BusMaterialSrm busMaterialSrm = new BusMaterialSrm();
            if(!pmsSrm04.getDetail().stream().anyMatch(detail->ApiConstants.FB_CONTRACT_CHANGE == detail.getChangeFlag())) {
                // 项目ID
                busMaterialSrm.setProjectId(busProject.getProjectId());
                // 项目编码
                busMaterialSrm.setProjectCode(busProject.getProjectCode());
                // 专业代码
                busMaterialSrm.setMajorCode(PmsToolUtil.getStrValue(headerPackageData, ApiConstants.INVOKE_GET_MAJORCODE));
                // 工程包代码
                busMaterialSrm.setPackageCode(PmsToolUtil.getStrValue(headerPackageData, ApiConstants.INVOKE_GET_PACKAGENO));
                // 需求计划单号为0L
                busMaterialSrm.setPlandtlId(0L);
                busMaterialSrmService.save(busMaterialSrm);
            }
            BusSupplier busSupplier = pmsApiUtil.getBusSupplier(null, pmsSrm04.getVendorNo());

            List<BusMaterialSrmSub> busMaterialSrmSubListForIns = Lists.newArrayList();
            List<BusMaterialSrmSub> busMaterialSrmSubListForUpds = Lists.newArrayList();
            pmsSrm04.getDetail().stream().forEach(detailReq -> {
                // 分包合同明细为非变更时,同时该为新创建合同明细
                // if (checkFbContractChange(detailReq, busSupplier.getSupplierId())) {
                BusMaterialSrmSub busMaterialSrmSub;
                if (checkFbContractChange(detailReq)) {
                    busMaterialSrmSub = new BusMaterialSrmSub();

                    // 项目ID
                    busMaterialSrmSub.setProjectId(busProject.getProjectId());
                    // 项目编码
                    busMaterialSrmSub.setProjectCode(busProject.getProjectCode());
                    // 专业代码
                    busMaterialSrmSub.setMajorCode(PmsToolUtil.getStrValue(headerPackageData, ApiConstants.INVOKE_GET_MAJORCODE));
                    // 工程包代码
                    busMaterialSrmSub.setPackageCode(PmsToolUtil.getStrValue(headerPackageData, ApiConstants.INVOKE_GET_PACKAGENO));

                    busMaterialSrmSub.setVer(detailReq.getVer());
                    busMaterialSrmSub.setMaterialPackageId(detailReq.getMaterialPackageIds());
                    // 关联主表
                    busMaterialSrmSub.setBusMaterialSrmId(busMaterialSrm.getBusMaterialSrmId());
                    busMaterialSrmSub.setOrderFlg(ApiConstants.ORDER_FLG_OFF);

                    // 供应商信息
                    busMaterialSrmSub.setSupplierId(busSupplier.getSupplierId());
                    busMaterialSrmSub.setSupplierCode(pmsSrm04.getVendorNo());
                    busMaterialSrmSub.setSupplierName(busSupplier.getSupplierName());

                    // 合同信息
                    busMaterialSrmSub.setContractNo(pmsSrm04.getContractNo());
                    busMaterialSrmSub.setContractsId(pmsSrm04.getContractId());
                    busMaterialSrmSub.setContractsmatdtlId(detailReq.getContractsmatdtlId());
                    busMaterialSrmSub.setContractRowno(detailReq.getContractRowno());

                    // 订单信息
                    busMaterialSrmSub.setPurchaseorderNo(pmsSrm04.getPurchaseOrderNo());
                    busMaterialSrmSub.setPurchaseorderId(pmsSrm04.getPurchaseOrderId());
                    busMaterialSrmSub.setPurchaseorderDetailid(detailReq.getPurchaseOrderDetailId());
                    busMaterialSrmSub.setPurchaseorderRowno(detailReq.getRowids());
                    busMaterialSrmSub.setWbs(detailReq.getWbs());
                    busMaterialSrmSub.setMaterialCode(detailReq.getMaterialCode());
                    busMaterialSrmSub.setMaterialName(detailReq.getMaterialName());
                    // 订单数量
                    busMaterialSrmSub.setOrderQty(detailReq.getOrderQty());
                    busMaterialSrmSub.setPmsPrice(detailReq.getPmsPrice());
                    busMaterialSrmSub.setPmsCount(detailReq.getPmsCount());
                    // 剩余数量
                    busMaterialSrmSub.setOrderSurplusQty(detailReq.getOrderQty());

                    // 送货单信息
                    busMaterialSrmSub.setDeliveryId(detailReq.getDeliveryId());
                    busMaterialSrmSub.setShoppingNoticeDetailId(detailReq.getShoppingNoticeDetailId());
                    busMaterialSrmSub.setShoppingNoticeRowId(detailReq.getShoppingNoticeRowId());

                    busMaterialSrmSubListForIns.add(busMaterialSrmSub);
                } else {
                    busMaterialSrmSub = pmsApiUtil.getBusMaterialSrmSubsBySrmContractDetailId(detailReq.getContractsmatdtlId(), detailReq.getContractRowno());
                    busMaterialSrmSub.setOrderQty(detailReq.getOrderQty());
                    busMaterialSrmSub.setOrderOutQty(detailReq.getOrderQty());
                    busMaterialSrmSub.setOrderSurplusQty(detailReq.getOrderQty());
                    busMaterialSrmSub.setPmsCount(detailReq.getPmsCount());
                    busMaterialSrmSubListForUpds.add(busMaterialSrmSub);
                }

            });
            if(0 != busMaterialSrmSubListForIns.size()) {
                busMaterialSrmSubService.saveBatch(busMaterialSrmSubListForIns);
                Map<Long, Long> srmIdPackageIdMap = Maps.newHashMap();
                busMaterialSrmSubListForIns.stream().forEach(srmSubObj -> {
                    srmIdPackageIdMap.put(srmSubObj.getMaterialPackageId(), srmSubObj.getBusMaterialSrmSubId());
                });

                if(0 != srmIdPackageIdMap.size()) {
                    // 100分包计划更新
                    if (pmsApiUtil.getLastVer(busProject.getProjectId(), 1)) {
                        List<BusMaterialPackage100> package100s = pmsApiUtil.getPackage100List(busProject.getProjectId(), majorCode, packageNo);
                        List<BusMaterialPackage100> package100Upds = Lists.newArrayList();
                        package100s.stream().forEach(package100Obj -> {
                            if (srmIdPackageIdMap.containsKey(package100Obj.getMaterialPackage100Id())) {
                                pmsSrmApiSubService.setSrmPackageId(package100Obj, busProjectSupplier, srmIdPackageIdMap.get(package100Obj.getMaterialPackage100Id()), busSupplier.getSupplierId());
                                package100Upds.add(package100Obj);
                            }
                        });
                        package100Service.updateBatchById(package100Upds);
                    } else {
                        // 200分包计划更新
                        List<BusMaterialPackage200> package200s = pmsApiUtil.getPackage200List(busProject.getProjectId(), majorCode, packageNo);
                        List<BusMaterialPackage200> package200Upds = Lists.newArrayList();
                        package200Upds.stream().forEach(package200Obj -> {
                            if (srmIdPackageIdMap.containsKey(package200Obj.getPackagePlan100Id())) {
                                pmsSrmApiSubService.setSrmPackageId(package200Obj, busProjectSupplier, srmIdPackageIdMap.get(package200Obj.getMaterialPackage100Id()), busSupplier.getSupplierId());
                                package200Upds.add(package200Obj);
                            }
                        });
                        package200Service.updateBatchById(package200Upds);
                    }
                }
            }

            if(0 != busMaterialSrmSubListForUpds.size()) {
                busMaterialSrmSubService.updateBatchById(busMaterialSrmSubListForUpds);
            }

            BusProjectPackSyncSrm busProjectPackSyncSrm = pmsApiUtil.getBusProjectPackSyncSrm(busProject.getProjectId(), majorCode, packageNo);
            if (null != busProjectPackSyncSrm) {
                StaticLog.debug("更新BusProjectPackSyncSrm----start");
                for (int i = 1; i < ApiConstants.INT_ELEVEN; i++) {
                    Long supplierIdForSync = PmsToolUtil.getLongValue(busProjectPackSyncSrm, ApiConstants.INVOKE_GET_SUPPLIERID + i);
                    if (!supplierIdForSync.equals(0L) && supplierIdForSync.equals(busSupplier.getSupplierId())) {
                        PmsToolUtil.setValue(busProjectPackSyncSrm, ApiConstants.INVOKE_SET_SYNCSTATUS + i, ApiConstants.PACKAGE_SRM_SYNC_SUCESS);
                    }
                }
                pmsApiUtil.updateBusProjectPackSyncSrm(busProjectPackSyncSrm);
                StaticLog.debug("更新BusProjectPackSyncSrm----end");
            } else {
                throw new Exception("busProjectPackSyncSrm 数据丢失");
            }
        } else {
            Map<Long, BusMaterialSrm> srmDataMap = Maps.newHashMap();
            BusMaterialSrm busMaterialSrmHeader = pmsApiUtil.getBusMaterialSrm(pmsSrm04.getDetail().get(0).getPurchaseId(), pmsSrm04.getDetail().get(0).getPurchaseDetailsId());
            Integer ver = pmsApiUtil.getLastVer(busMaterialSrmHeader.getProjectId(), 0) ? ApiConstants.VER_100 : ApiConstants.VER_200;
            pmsSrm04.getDetail().stream().forEach(detailReq -> {
                BusMaterialSrm busMaterialSrm = pmsApiUtil.getBusMaterialSrm(detailReq.getPurchaseId(), detailReq.getPurchaseDetailsId());
                List<BusMaterialSrmSub> busMaterialSrmSubList = Lists.newArrayList();
                List<BusDeliverSrm> busDeliverSrmList = Lists.newArrayList();
                if (srmDataMap.containsKey(detailReq.getPurchaseDetailsId())) {
                    busMaterialSrm = srmDataMap.get(detailReq.getPurchaseDetailsId());
                    busMaterialSrmSubList = busMaterialSrm.getBusMaterialSrmSubList();
                }

                BusMaterialSrmSub busMaterialSrmSub = new BusMaterialSrmSub();
                busMaterialSrmSub.setVer(ver);
                busMaterialSrmSub.setPurchaseId(detailReq.getPurchaseId());
                busMaterialSrmSub.setPurchaseDetailsId(detailReq.getPurchaseDetailsId());
                busMaterialSrmSub.setMaterialPlanId(busMaterialSrm.getMaterialPlanId());
                busMaterialSrmSub.setOrderFlg(ApiConstants.ORDER_FLG_OFF);

                // 合同信息
                busMaterialSrmSub.setContractNo(pmsSrm04.getContractNo());
                busMaterialSrmSub.setContractsId(pmsSrm04.getContractId());
                busMaterialSrmSub.setContractsmatdtlId(detailReq.getContractsmatdtlId());
                busMaterialSrmSub.setContractRowno(detailReq.getContractRowno());
                // 订单信息
                busMaterialSrmSub.setPurchaseorderNo(pmsSrm04.getPurchaseOrderNo());
                busMaterialSrmSub.setPurchaseorderId(pmsSrm04.getPurchaseOrderId());
                busMaterialSrmSub.setPurchaseorderDetailid(detailReq.getPurchaseOrderDetailId());
                busMaterialSrmSub.setPurchaseorderRowno(detailReq.getRowids());
                // 送货单信息
                busMaterialSrmSub.setDeliveryId(detailReq.getDeliveryId());
                busMaterialSrmSub.setShoppingNoticeDetailId(detailReq.getShoppingNoticeDetailId());
                busMaterialSrmSub.setShoppingNoticeRowId(detailReq.getShoppingNoticeRowId());

                busMaterialSrmSubList.add(busMaterialSrmSub);
                busMaterialSrm.setBusMaterialSrmSubList(busMaterialSrmSubList);
                srmDataMap.put(detailReq.getPurchaseDetailsId(), busMaterialSrm);

            });
            if (0 == srmDataMap.size()) {
                return;
            }

            srmDataMap.forEach((purchaseDetailsId, srmObj) -> {
                Long busMaterialSrmId = pmsApiUtil.getBusMaterialSrm(srmObj.getPurchaseId(), srmObj.getPurchaseDetailsId()).getBusMaterialSrmId();
                srmObj.getBusMaterialSrmSubList().stream().forEach(srmSub -> {
                    srmSub.setBusMaterialSrmId(busMaterialSrmId);
                    busMaterialSrmSubService.save(srmSub);
                });
            });
        }

    }

    // 材料在SRM点收审核，成功收货后，在该次收货完成的同时调用PMS收货信息接口，把收货信息回传给PMS。同理如果发生收货冲销也回传PMS。
    @ApiOperation(value = "SRM收货信息同步 : pms05")
    public void pms05(PmsSrm05 pmsSrm05) {
        pmsSrm05.getDetail().stream().forEach(pm05Obj -> {
            // SRM送货单关联信息更新
            BusDeliverSrm busDeliverSrm = new BusDeliverSrm();
            BeanUtil.copyProperties(pm05Obj, busDeliverSrm);
            BusMaterialSrmSub busMaterialSrmSub = pmsApiUtil.getBusMaterialSrmSub(busDeliverSrm.getPurchaseId(), busDeliverSrm.getPurchaseDetailsId());
            busDeliverSrm.setBusMaterialSrmSubId(busMaterialSrmSub.getBusMaterialSrmSubId());
            if (null != busMaterialSrmSub.getDeliveryId() && !busMaterialSrmSub.getDeliveryId().equals(0L)) {
                busDeliverSrm.setDeliverId(busMaterialSrmSub.getDeliveryId());
            }
            busDeliverSrmService.save(busDeliverSrm);
            if (StrUtil.isNotEmpty(pmsSrm05.getDetail().get(0).getMaterialCode())) {
                // PMS材料申请计划更新
//                pmsSrm05.getDetail().stream().forEach(pms05Obj->{
                BusPurchaseDetails details = busPurchaseDetailsService.getById(pm05Obj.getPurchaseDetailsId());
                // 在途数量
                details.setOnLineNum(NumberUtil.sub(details.getOnLineNum(), pm05Obj.getQtyReceive()));
                // 到货数量
                details.setReceiveNum(NumberUtil.add(details.getReceiveNum(), pm05Obj.getQtyReceive()));
                busPurchaseDetailsService.updateById(details);
//                });
                // 材料计划
                if (PmsToolUtil.checkLong(busMaterialSrmSub.getMaterialPlanId())) {
                    if (ApiConstants.VER_100 == busMaterialSrmSub.getVer()) {
                        BusMaterialPlan100 busMaterialPlan100 = busMaterialPlan100Service.getById(busMaterialSrmSub.getMaterialPlanId());
                        // 到货量 = 计划中到货量 + 本次收货数量
                        busMaterialPlan100.setDhPurchaseCount(NumberUtil.add(busMaterialPlan100.getDhPurchaseCount(), pm05Obj.getQtyReceive()));
                        // 在途采购量 = 计划中在途数量 - 本次收货数量
                        busMaterialPlan100.setZtPurchaseCount(NumberUtil.sub(busMaterialPlan100.getZtPurchaseCount(), pm05Obj.getQtyReceive()));
                        busMaterialPlan100Service.updateById(busMaterialPlan100);
                    } else {
                        BusMaterialPlan200 busMaterialPlan200 = busMaterialPlan200Service.getById(busMaterialSrmSub.getMaterialPlanId());
                        // 到货量 = 计划中到货量 + 本次收货数量
                        busMaterialPlan200.setDhPurchaseCount(NumberUtil.add(busMaterialPlan200.getDhPurchaseCount(), pm05Obj.getQtyReceive()));
                        // 在途采购量 = 计划中在途数量 - 本次收货数量
                        busMaterialPlan200.setZtPurchaseCount(NumberUtil.sub(busMaterialPlan200.getZtPurchaseCount(), pm05Obj.getQtyReceive()));
                        busMaterialPlan200Service.updateById(busMaterialPlan200);
                    }
                }
            }

            if (null == busMaterialSrmSub && busMaterialSrmSub.equals(0L)) {
                BusPurchaseDetails updDetail = busPurchaseDetailsService.getById(pm05Obj.getPurchaseDetailsId());
                // 到货量 = 材料申请中到货量 + 本次收货数量
                updDetail.setReceiveNum(NumberUtil.add(updDetail.getReceiveNum(), pm05Obj.getQtyReceive()));
                // 在途采购量 = 材料申请中在途数量 - 本次收货数量
                updDetail.setOnLineNum(NumberUtil.sub(updDetail.getOnLineNum(), pm05Obj.getQtyReceive()));
                busPurchaseDetailsService.updateById(updDetail);
            }

        });

    }

    //    物资到货，超收过送货单数量时，
//    超出的数量，材料员会记录到SRM送货点收审核页面中，材料员提交该笔点收后
//    SRM发起送货单超收信息到PMS，通知工程师进行补单。
//    系统参数追加，该功能开关。
    public void pms06(PmsSrm06 pmsSrm06) {
        // TODO:系统通知功能
        // TODO: 材料申请自动创建功能

    }

    // 以上接口，异步类型的接口调用时，如SRM的运行错误，需要调用此接口进行错误通知。
    public void pms07(PmsSrm07 pmsSrm07) {
        BusSrmApiExpLog busSrmApiExpLog = new BusSrmApiExpLog();
        pmsLogUtil.saveBusSrmApiExpLog(pmsSrm07.getExceptionNm(), pmsSrm07.getContent());

    }

    private BusProject getBusProjectForPms04(Integer ver, Long materialPackageIds) {
        BusProject busProject = new BusProject();
        Long projectId = 0L;
        if (ApiConstants.VER_100 == ver) {
            BusMaterialPackage100 busMaterialPackage100 = package100Service.getById(materialPackageIds);
            projectId = busMaterialPackage100.getProjectId();
        } else {
            BusMaterialPackage200 busMaterialPackage200 = package200Service.getById(materialPackageIds);
            projectId = busMaterialPackage200.getProjectId();
        }
        return busProjectService.getById(projectId);
    }

    /**
     * 判断分包合同是否为新创建的
     * @param detailReq
     * @return
     */
    private Boolean checkFbContractChange(PmsSrm04Detail detailReq) {
        Boolean ckRs = Boolean.FALSE;
        // 分包合同明细为非变更时
        if (ApiConstants.FB_CONTRACT_UN_CHANGE == detailReq.getChangeFlag()) {
            BusMaterialSrmSub busMaterialSrmSub = pmsApiUtil.getBusMaterialSrmSubsBySrmContractDetailId(detailReq.getContractsmatdtlId(), detailReq.getContractRowno());
            if(null == busMaterialSrmSub) {
                ckRs = Boolean.TRUE;
            }
        }
        return ckRs;
    }

    @ApiOperation(value = "分包合同驳回反冲同步 : pms08")
    public PMSResultBody pms08(PmsSrm08 pmsSrm08) throws Exception {
        //更新分包 bus_project_pack_sync_srm 对应的供应商的合同同步状态
        StaticLog.debug("分包合同驳回反冲同步 更新分包 bus_project_pack_sync_srm 对应的供应商的合同同步状态----start");
        //获取供应商信息
        BusSupplier supplier = supplierService.getByProperty(ApiConstants.MAP_SUPPLIERCODE, pmsSrm08.getVendorNo());
        //获取项目信息
        BusProject project = busProjectService.findByProjectCode(pmsSrm08.getProjectCode());
        //获取合同状态关系数据
        BusProjectPackSyncSrm busProjectPackSyncSrm = pmsApiUtil.getBusProjectPackSyncSrm(project.getProjectId(), pmsSrm08.getMajorCode(), pmsSrm08.getPackageNo());
        if (null != busProjectPackSyncSrm) {
            StaticLog.debug("更新BusProjectPackSyncSrm----start");
            for (int i = 1; i < ApiConstants.INT_ELEVEN; i++) {
                Long supplierIdForSync = PmsToolUtil.getLongValue(busProjectPackSyncSrm, ApiConstants.INVOKE_GET_SUPPLIERID + i);
                if (!supplierIdForSync.equals(0L) && supplierIdForSync.equals(supplier.getSupplierId())) {
                    PmsToolUtil.setValue(busProjectPackSyncSrm, ApiConstants.INVOKE_SET_SYNCSTATUS + i, ApiConstants.PACKAGE_SRM_SYNC_FAIL);
                }
            }
            pmsApiUtil.updateBusProjectPackSyncSrm(busProjectPackSyncSrm);
            StaticLog.debug("分包合同驳回反冲同步 更新分包 bus_project_pack_sync_srm 对应的供应商的合同同步状态----end");
        } else {
            StaticLog.debug("分包合同驳回反冲同步源数据不存在");
//            throw new Exception("busProjectPackSyncSrm 数据丢失");
            return PMSResultBody.err("分包合同驳回反冲同步源数据不存在");
        }
        return PMSResultBody.ok("处理正常");
    }

    @ApiOperation(value = "送货取消或者关闭反冲同步 : pms09")
    public PMSResultBody pms09(List<PmsSrm09> pmsSrm09s) throws Exception {
        if(CollectionUtils.isEmpty(pmsSrm09s)) {
            return PMSResultBody.err("请求回置参数不能为空");
        }
        //月报记录主键ID
        List<Long> busReportIds = Lists.newArrayList();
        //记录与回置数量map
        Map<Long, BigDecimal> resetQtyMap = Maps.newHashMap();
        for(PmsSrm09 item: pmsSrm09s) {
            busReportIds.add(item.getReportId());
            resetQtyMap.put(item.getReportId(), item.getQuantity());
        }
        //获取月报数据
        CriteriaQuery<BusReport> cu = new CriteriaQuery(BusReport.class);
        cu.in("reportId", busReportIds);
        List<BusReport> reports = busReportService.list(cu);
        if(CollectionUtils.isEmpty(reports)) {
            return PMSResultBody.err("月报源记录不存在，请检查");
        }
        //回置数量
        StaticLog.debug("送货取消或者关闭反冲同步---start");
        for(BusReport item: reports) {
            //获取分包价格
            BusMaterialSrmSub busMaterialSrmSubHeader = pmsApiUtil.getBusMaterialSrmSubForPackageForPms04(item.getMaterialId(), item.getSupplierId(),
                Integer.valueOf(item.getVer()), item.getPackageNo());
            if(busMaterialSrmSubHeader != null) {
                //扣减数量 = 回置数量/分包价格
                BigDecimal reduceQty = resetQtyMap.get(item.getReportId()).divide(busMaterialSrmSubHeader.getPmsPrice(), 5, BigDecimal.ROUND_HALF_UP);
                item.setConfirmQuantity(item.getConfirmQuantity().subtract(reduceQty));
            }
        }
        //更新数据
        busReportService.saveOrUpdateBatch(reports);
        StaticLog.debug("送货取消或者关闭反冲同步---end");
        return PMSResultBody.ok("处理正常");
    }

}
